import { useEffect } from 'react'
import { useSelector } from 'react-redux'
import { useDispatch } from 'react-redux'
import { getArticles } from './store/actions/article'
import { changeActive, getChannels } from './store/actions/channel'

export default function App() {
  return (
    <>
      {/* 头部频道 */}
      <Channel />
      {/* 文章列表 */}
      <Article />
    </>
  )
}

function Channel() {
  // 组件挂载完毕后，发送请求获取频道数据
  const dispatch = useDispatch()
  useEffect(() => {
    // 通过 dispatch 调用异步 action
    dispatch(getChannels())
  }, [dispatch])

  const { list, active } = useSelector((state) => state.channel)

  return (
    <ul className='catagtory'>
      {list.map((item) => (
        <li
          key={item.id}
          className={item.id === active ? 'select' : ''}
          onClick={() => dispatch(changeActive(item.id))}
        >
          {item.name}
        </li>
      ))}
    </ul>
  )
}

function Article() {
  const dispatch = useDispatch()
  // 获取选中的频道 id
  const { active } = useSelector((state) => state.channel)
  const { list } = useSelector((state) => state.article)

  useEffect(() => {
    // 相当于 vue 里面的 watch，监听 active 变化重新发送请求
    dispatch(getArticles({ channel_id: active }))
  }, [dispatch, active])

  return (
    <div className='list'>
      {list.map((item) => (
        <div key={item.art_id} className='article_item'>
          <h3 className='van-ellipsis'>{item.title}</h3>
          {item.cover.type !== 0 ? (
            <div className='img_box'>
              <img src={item.cover.images[0]} className='w100' alt='' />
            </div>
          ) : null}
          <div className='info_box'>
            <span>{item.aut_name}</span>
            <span>{item.comm_count} 评论</span>
            <span>{item.pubdate}</span>
          </div>
        </div>
      ))}
    </div>
  )
}
